<?php

namespace app\admin\controller\yalimedia\question;

use app\common\controller\Backend;
use addons\exam\model\QuestionModel;
use app\common\model\CourseQuestion;
use app\common\model\YalimediaQuestionLogDetail as LogDetail;

/**
 * 用户答题记录
 *
 * @icon fa fa-circle-o
 */
class Detail extends Backend
{

    /**
     * Detail模型对象
     * @var \app\admin\model\yalimedia\question\Detail
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model    = new \app\admin\model\yalimedia\question\Detail;
        $this->LogModel = new \app\admin\model\yalimedia\question\Log;

    }

/*    “不光是热情，他们也是真心的感激先生。*/


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function list($ids='')
    {
        $this->relationSearch = true;
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
            $row          = $this->LogModel->get($ids);
            $course_id    = $row['course_id']; // 课程ID
            $question_ids = CourseQuestion::where(['cate_id'=>$course_id])->column('question_id');

            $list   = QuestionModel::getQuestion($question_ids);
            
            $list   = $list['data'] ?? [];
            $questions = [];
            if(!empty($list)){
                foreach ($list as $value) {
                    $material_questions = $value['material_questions'] ?? [];
                    if ($material_questions) {
                        $questions = array_merge(array_values($questions), $material_questions);
                    }else{
                    
                        $questions = array_merge(array_values($questions), [$value]);
                    }
                }
            }

            $detail = LogDetail::where(['log_id'=>$ids])->field('question_id,content')->column('content','question_id');
          
            foreach ($questions as &$value) {
                if(!isset($detail[$value['id']])){
                    $value['user_answer']  = [];
                }else{
                    $value['user_answer']  = \json_decode($detail[$value['id']],true);
                }
            }
            
            $result = array("total" => count($list), "rows" => $questions);
            return json($result);
        }
        
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }

}
